import {Component, forwardRef, OnInit} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import * as _ from 'lodash';

import {ConfigService} from '@kylin/config';
import {UploadFile} from 'ng-zorro-antd';
import {HttpService} from '@kylin/http';

export const UPLOAD_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => UploadComponent),
    multi: true
};

@Component({
    selector: 'kylin-upload',
    templateUrl: './upload.component.html',
    styleUrls: ['./upload.component.less'],
    providers: [UPLOAD_VALUE_ACCESSOR]
})
export class UploadComponent implements OnInit, ControlValueAccessor {

    uploadPath = '/resource';
    fileList = [];
    imgHostname: string;
    previewImage = '';
    previewVisible = false;

    constructor(private configService: ConfigService,
                private http: HttpService) {
        this.imgHostname = configService.imgHostname;
    }

    ngOnInit() {
    }

    handlePreview = (file: UploadFile) => {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
    };

    uploadChange(event) {
        if (event.type === 'success') {
            this.fileList = this.fileList.map(target => {
                if (target.status === 'done') {
                    return {uid: target.uid, url: this.imgHostname + target.response.result[0]};
                } else {
                    return target;
                }
            });
            this.propagateChange(this.handleResponseUploadInfo(this.fileList));
        }
    }

    uploadRemove = (target): boolean => {
        this.fileList.map(value => {
            if (value.status === 'removed') {
                this.http.delete(this.uploadPath, {filePaths: this.handleImgUrl(value.url)})
                    .then(res => {

                    })
                    .catch(err => {

                    });
            }
        });
        this.fileList = _.compact(this.fileList.map(value => {
            if (value.status !== 'removed') {
                return value;
            }
        }));
        this.propagateChange(this.handleResponseUploadInfo(this.fileList));
        return true;
    };

    propagateChange = (data: any) => { // 相当于output功能,用于把改变的值传输出去

    };

    writeValue(value: any) { // 该方法用于将模型中的新值写入视图或 DOM 属性中
        if (!_.isEmpty(value)) {
            this.fileList = [];
            value.map((e, index) => {
                if (_.isObject(e)) {
                    this.fileList.push(e);
                } else {
                    this.fileList.push({uid: index, url: this.imgHostname + e});
                }
            });
        } else {
            this.fileList = [];
        }
    }

    registerOnChange(fn: (data: any) => void): void {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any) {
    }

    private handleImgUrl(url: string): string {
        if (url) {
            return url.replace(this.imgHostname, '');
        } else {
            return '';
        }
    }

    private handleResponseUploadInfo(value: any[]) {
        const result = [];
        value.map(e => {
            result.push(this.handleImgUrl(e.url));
        });
        return result;
    }

}
